<template>
  <div class="json-editor">
    <textarea ref="textarea" />
  </div>
</template>

<script setup name="JsonEditor">
import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/rubyblue.css'
//import 'script-loader!jsonlint'
import 'codemirror/mode/javascript/javascript'
import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/json-lint'

const props = defineProps(['value'])
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const jsonEditor = ref(false)

watch(
  () => props.value,
  (value) => {
    const editorValue = jsonEditor.value.getValue()
    if (value !== editorValue) {
      jsonEditor.value.setValue(JSON.stringify(props.value, null, 2))
    }
  }
)

onMounted(() => {
  jsonEditor.value = CodeMirror.fromTextArea(proxy.$refs.textarea, {
    lineNumbers: true,
    mode: 'application/json',
    gutters: ['CodeMirror-lint-markers'],
    theme: 'rubyblue',
    lint: true,
  })
  jsonEditor.value.setValue(JSON.stringify(props.value, null, 2))
  jsonEditor.value.on('change', (cm) => {
    emits('changed', cm.getValue())
    emits('input', cm.getValue())
  })
})

function getValue() {
  return jsonEditor.value.getValue()
}
</script>

<style scoped>
.json-editor {
  height: 100%;
  position: relative;
}
.json-editor :deep(.CodeMirror) {
  height: auto;
  min-height: 300px;
}
.json-editor :deep(.CodeMirror-scroll) {
  min-height: 300px;
}
.json-editor :deep(.cm-s-rubyblue) span.cm-string {
  color: #f08047;
}
</style>
